import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva/index';
import {
  Spin,
  Row,
  Empty,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Table,
  Popconfirm,
} from 'antd/lib/index';
import moment from 'moment/moment';
import router from 'umi/router';
import { Mover } from '@/function.js';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BillUpload from './BillUpload';

import styles from '../FundPosition/Test.less';
import styles1 from './RYBill.less';
import WrappedDynamicFieldSet from './DynamicFieldSet';
import { DateStamp, empty } from '../../../function';

const UeserName = localStorage.getItem('antd-pro-authority').slice(2, -2);
const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

/* eslint react/no-multi-comp:0 */
@connect(({ fund, loading }) => ({
  fund,
  loading: loading.models.ruleTest,
}))
@Form.create()
class MGHGBill extends PureComponent {
  state = {
    filterData: [],
    expandForm: false, // 查询菜单栏 是否显示
    listLoading: false,
    formValues: {
      billType: 0, // 全部类型
      stock: '',
      orderItem: 0,
      orderType: 0,
      productId: 6, // 1是 瑞银
      billMinToStrikePriceRate: null,
    }, // 查询菜单栏   查询参数
    modalVisible: false,
    updateModalVisible: false,
    BillUploadVisible: false, // modal开关
    liquidationModalVisible: false, // 平仓modal
    liquidationRecord: {},
    isUpdate: false,
    selectedRows: [],

    stepFormValues: {},

    dataTradeList: {},
    updateParam: true,

    HistogramModalVisible: false,
    record: {},

    suggestions: [],
    textboxValues: {
      key: '',
      type: 1,
    },
  };

  indexCountColumns = [];

  groupRender = (value, row, index) => {
    const obj = {
      children: value,
      props: {},
    };
    if (this.indexCountColumns.length > 0) {
      let isHave = false;
      for (let i = 0; i < this.indexCountColumns.length; i++) {
        if (index === this.indexCountColumns[i].index) {
          isHave = true;
          obj.props.rowSpan = this.indexCountColumns[i].count;
        }
      }
      if (!isHave) {
        if (value) {
          obj.props.rowSpan = 0;
          obj.props.colSpan = 0;
        } else {
          obj.props.rowSpan = 0;
        }
      }
    }
    return obj;
  };

  renderContentBase = (value, row, index) => {
    const obj = {
      children: value,
      props: {},
    };
    return obj;
  };

  groupRenderBillId = (value, row, index) => {
    const obj = {
      children: value,
      props: {},
    };
    if (this.indexCountColumns.length > 0) {
      let isHave = false;
      for (let i = 0; i < this.indexCountColumns.length; i++) {
        if (index === this.indexCountColumns[i].index) {
          isHave = true;
          obj.props.rowSpan = this.indexCountColumns[i].count;
        }
      }
      if (!isHave) {
        if (value) {
          obj.props.rowSpan = 0;
          obj.props.colSpan = 0;
        }
      }
    }

    let priceratetext = '';
    if (value >= 0) {
      priceratetext = value * 100;
      priceratetext = `${priceratetext.toFixed(2)}%`;
    }
    obj.children = <span>{priceratetext}</span>;
    return obj;
  };

  groupRenderBillIdAction = (value, record, index) => {
    const obj = {
      children: value,
      props: {},
    };

    if (this.indexCountColumns.length > 0) {
      let isHave = false;
      for (let i = 0; i < this.indexCountColumns.length; i++) {
        if (index === this.indexCountColumns[i].index) {
          isHave = true;
          obj.props.rowSpan = this.indexCountColumns[i].count;
        }
      }
      if (!isHave) {
        if (value) {
          obj.props.rowSpan = 0;
          obj.props.colSpan = 0;
        }
      }
    }
    obj.children =
      index > 0 ? (
        <Fragment>
          <a
            style={{ marginRight: '4px' }}
            onClick={this.liquidationCurrentData.bind(this, record)}
          >
            平仓
          </a>
          <div/><br/>
          <a onClick={this.updateCurrentData.bind(this, record)}>修改</a>

        </Fragment>
      ) : (
        <div />
      );
    return obj;
  };

  updateCurrentData(record) {
    this.setState({
      record,
      isUpdate: true,
      BillUploadVisible: true,
    });
  }

  deleteCurrentData(record) {
    const { dispatch } = this.props;
    dispatch({
      type: 'fund/BgDeleteBillData',
      payload: {
        id: record.pid,
        userName: localStorage.getItem('antd-pro-authority').slice(2, -2),
      },
      callback: res => {
        this.componentDidMount();
      },
    });
  }

  columns = [
    {
      title: '序号',
      dataIndex: 'billId',
      render: this.groupRender,
      key: 'billId',
      width: 70,
    },
    {
      title: '编号',
      dataIndex: 'billNumber',
      render: this.groupRender,
      key: 'billNumber',
      width: 170,
    },
    {
      title: '类型',
      dataIndex: 'name',
      render: this.groupRender,
      width: 130,
      key: 'name',
    },
    {
      title: '票据',
      dataIndex: 'stock',
      render: this.renderContentBase,
      key: 'stock',
      width: 110,
    },
    {
      title: '市场价',
      dataIndex: 'marketValue',
      render: this.renderContentBase,
      key: 'marketValue',
      width: 100,
    },
    {
      title: '执行价',
      dataIndex: 'strikePrice',
      render: this.renderContentBase,
      key: 'strikePrice',
      width: 100,
    },

    {
      title: '可赎回价格',
      dataIndex: 'redeemablePrice',
      render: this.renderContentBase,
      key: 'redeemablePrice',
      width: 120,
    },
    {
      title: '距离执行价',
      dataIndex: 'toStrikePriceRate',
      key: 'toStrikePriceRate',
      sorter: true,
      width: 130,
      render:(value, row, index) => {
        let color;
        if (row.ifMinToStrikePriceRateStock ) {
          color = 'rgba(255, 130, 130)';
        }else {
          color = 'rgba(255, 77, 79,0)';
        }
        return (
          <div
            style={{
              background: color,
              margin: '-17px',
              border: '15px solid ',
              borderColor: color,
            }}
          >
            <span>{value}</span>
          </div>
        );
      },
    },
    {
      title: 'KI',
      dataIndex: 'ki',
      render: this.renderContentBase,
      key: 'ki',
      width: 150,
    },
    {
      title: '距离安全垫幅度',
      dataIndex: 'toSaveRateRate',
      key: 'toSaveRateRate',
      width: 140,
      render: this.renderContentBase,
    },
    {
      title: '票息',
      dataIndex: 'billCoupon',
      render: this.groupRenderBillId,
      key: 'billCoupon',
      width: 100,
      sorter: true,
    },
    {
      title: '每月盈利',
      dataIndex: 'billMonthEarn',
      render: this.groupRender,
      key: 'billMonthEarn',
      width: 120,
    },
    {
      title: '每月利息金额',
      dataIndex: 'monthInterestAmount',
      render: this.groupRender,
      key: 'monthInterestAmount',
      width: 120,
    },

    {
      title: '折扣率',
      dataIndex: 'discountRate',
      render: this.groupRenderBillId,
      key: 'discountRate',
      width: 100,
      sorter: true,
    },
    {
      title: '可赎回类别',
      dataIndex: 'redeemableType',
      render: this.groupRender,
      key: 'redeemableType',
      width: 100,
    },
    {
      title: '金额（美元）',
      dataIndex: 'amountOfMoney',
      render: this.groupRender,
      key: 'amountOfMoney',
      width: 140,
      sorter: (a, b) => {
        if (b.billId === '总计') {
          return false
        } else {
          return a.amountOfMoney - b.amountOfMoney
        }
      },
    },
    {
      title: '单据市值/日期',
      dataIndex: 'billMv',
      align:'center',
      render: (value, row, index) => {
        let obj = {
          children: <div>
            <div>{value}</div>
            <div/><br/>
            <div>{empty(row.billMvDate)?'':row.billMvDate.split(' ')[0]}</div>
          </div>,
          props: {},
        };
        if (this.indexCountColumns.length > 0) {
          let isHave = false;
          for (let i = 0; i < this.indexCountColumns.length; i++) {
            if (index === this.indexCountColumns[i].index) {
              isHave = true;
              obj.props.rowSpan = this.indexCountColumns[i].count;
            }
          }
          if (!isHave) {
            if (value) {
              obj.props.rowSpan = 0;
              obj.props.colSpan = 0;
            } else {
              obj.props.rowSpan = 0;
            }
          }
        }
        return obj;
      },
      key: 'billMv',
      width: 140,
      sorter: (a, b) => {
        if (a.billId === '总计') {
          return false;
        } else {
          return a.billMv - b.billMv
        }
      },
    },
    {
      title: '下一个比价日',
      dataIndex: 'laterParityDay',
      render: this.groupRender,
      key: 'laterParityDay',
      sorter: (a, b) => {
        if(a.billId=== '总计'){
          return false;
        }else{
          return DateStamp(a.laterParityDay) - DateStamp(b.laterParityDay)
        }
      },
      width: 120,
    },

    {
      title: '发行日期',
      dataIndex: 'discoveryDate',
      render: this.groupRender,
      key: 'discoveryDate',
      sorter: true,
      width: 120,
    },
    {
      title: '最终比价日期',
      dataIndex: 'finalPriceDate',
      render: this.groupRender,
      key: 'finalPriceDate',
      sorter: true,
      width: 140,
    },
    {
      title: '来源',
      dataIndex: 'origin',
      render: this.groupRender,
      key: 'origin',
      width: 100,
    },
    {
      title: '操作',
      // dataIndex: 'origin',
      // key: 'origin',
      width: 80,
      render: this.groupRenderBillIdAction,
    },
  ];

  // 菜单栏- 重置按钮 事件
  openBillUpload = () => {
    this.setState({
      record: {},
      BillUploadVisible: true,
      isUpdate: false,
    });
  };

  closeRecord() {
    const { dispatch } = this.props;
    this.setState(
      {
        BillUploadVisible: false,
      },
      () => {
        this.componentDidMount();
      }
    );
  }

  // 默认加载数据-起始方法
  render() {
    const {
      form: { getFieldDecorator },
      fund: { mghgBillData },
      loading,
      total,
    } = this.props;
    const {
      BillUploadVisible,
      isUpdate,
      record,

      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      listLoading,
    } = this.state;
    const newdata = {
      list: [],
      pagination: {
        total: 0,
      },
    };
    if (mghgBillData.code == 1) {
      newdata.list = mghgBillData.list;
      newdata.pagination = mghgBillData.pagination;
    }

    this.indexCountColumns = [];
    let indexTemp = 0;
    let countTemp = 1;

    let sumMonthInterestAmount = 0;
    let sumBillMonthEarn = 0;
    let sumAmountOfMoney = 0;
    if (newdata.list.length > 0) {
      newdata.list[0].monthInterestAmount = 0;
      newdata.list[0].billMonthEarn = 0;
      newdata.list[0].amountOfMoney = 0;
    }

    for (let i = 0; i < newdata.list.length; i++) {
      newdata.list[i].key = `00${i}`;
      if (newdata.list[i].billMonthEarn) {
        newdata.list[i].billMonthEarn = (
          Math.round(newdata.list[i].billMonthEarn * 100) / 100
        ).toString();
      }
      if (newdata.list[i].billCoupon) {
        newdata.list[i].billCoupon = parseFloat(newdata.list[i].billCoupon).toFixed(2);
      }
      if (newdata.list[i].discountRate) {
        newdata.list[i].discountRate = parseFloat(newdata.list[i].discountRate).toFixed(2);
      }
      if (newdata.list[i].marketValue) {
        newdata.list[i].marketValue = parseFloat(newdata.list[i].marketValue).toFixed(2);
      }
      if (newdata.list[i].strikePrice) {
        newdata.list[i].strikePrice = parseFloat(newdata.list[i].strikePrice).toFixed(2);
      }
      if (newdata.list[i].monthInterestAmount) {
        newdata.list[i].monthInterestAmount = parseFloat(
          newdata.list[i].monthInterestAmount
        ).toFixed(0);
      }
      if (newdata.list[i].discoveryDate && newdata.list[i].discoveryDate.length > 10) {
        newdata.list[i].discoveryDate = newdata.list[i].discoveryDate.substring(0, 10);
      }
      if (newdata.list[i].finalPriceDate && newdata.list[i].finalPriceDate.length > 10) {
        newdata.list[i].finalPriceDate = newdata.list[i].finalPriceDate.substring(0, 10);
      }

      if (i > 0) {
        if (newdata.list[i].billId === newdata.list[i - 1].billId) {
          countTemp++;
          newdata.list[i].monthInterestAmount = 0;
          newdata.list[i].billMonthEarn = 0;
          newdata.list[i].amountOfMoney = 0;
          if (i === newdata.list.length - 1) {
            this.indexCountColumns.push({
              index: indexTemp,
              count: countTemp,
            });
            newdata.list[indexTemp].productDataDetailForms = [];
            for (let j = indexTemp; j < indexTemp + countTemp; j++) {
              newdata.list[indexTemp].productDataDetailForms.push({
                payPrice: newdata.list[j].payPrice,
                investmentMoney: newdata.list[j].investmentMoney,
                ki: newdata.list[j].ki,
                bill: newdata.list[j].stock,
                id: newdata.list[j].id,
                exercisePrice: newdata.list[j].strikePrice,
                redeemablePrice: newdata.list[j].redeemablePrice,
              });
            }
          }
        } else {
          this.indexCountColumns.push({
            index: indexTemp,
            count: countTemp,
          });
          newdata.list[indexTemp].productDataDetailForms = [];
          for (let j = indexTemp; j < indexTemp + countTemp; j++) {
            newdata.list[indexTemp].productDataDetailForms.push({
              payPrice: newdata.list[j].payPrice,
              investmentMoney: newdata.list[j].investmentMoney,
              ki: newdata.list[j].ki,
              bill: newdata.list[j].stock,
              id: newdata.list[j].id,
              exercisePrice: newdata.list[j].strikePrice,
              redeemablePrice: newdata.list[j].redeemablePrice,
            });
          }

          indexTemp = i;
          countTemp = 1;
          if (i === newdata.list.length - 1) {
            this.indexCountColumns.push({
              index: indexTemp,
              count: countTemp,
            });
          }
        }
      }
      sumMonthInterestAmount += parseFloat(newdata.list[i].monthInterestAmount);
      sumBillMonthEarn += parseFloat(newdata.list[i].billMonthEarn);
      sumAmountOfMoney += parseFloat(newdata.list[i].amountOfMoney);
    }
    if (newdata.list.length > 0) {
      newdata.list[0].monthInterestAmount = sumMonthInterestAmount;
      newdata.list[0].amountOfMoney = sumAmountOfMoney;
      newdata.list[0].billMonthEarn = sumBillMonthEarn;
    }
    const { HistogramModalVisible } = this.state;
    const HistogramMethods = {
      handleHistogramVisible: this.handleHistogramVisible,
    };
    return (
      <PageHeaderWrapper title="华鸽票据列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.paginationMsg}>
              {'共'} {newdata.pagination.total} {'条数据'}
            </div>
            <br />

              <Table
                className={styles1.tableFixedRow}
                pagination={false}
                scroll={{ x: 2320, y: 650 }}
                columns={this.columns}
                onChange={this.handleStandardTableChange}
                dataSource={newdata.list}
                rowClassName={(record, index) => {
                  return parseFloat(record.toStrikePriceRate) < 0 ? styles.lineback : '';
                }}
                bordered
              />
          </div>
          <BillUpload
            record={record}
            title="上传摩根华鸽数据"
            isRy="6"
            isUpdate={isUpdate}
            RiskDetailVisible={BillUploadVisible}
            closeRecord={this.closeRecord.bind(this)}
          />
          <Modal
            title={`是否平仓(编号:${this.state.liquidationRecord.billNumber})?`}
            style={{ top: 100 }}
            width={300}
            visible={this.state.liquidationModalVisible}
            onOk={() => this.liquidationModalOk(false)}
            onCancel={() => this.liquidationModalCancel(false)}
          >
            <Form layout="horizontal">
              <FormItem>
                {getFieldDecorator('liquidationGrade', {
                  rules: [
                    {
                      required: true,
                      message: '请输入平仓水平',
                    },
                  ],
                })(<InputNumber min={1} placeholder="平仓水平" />)}
              </FormItem>
            </Form>
          </Modal>
        </Card>
      </PageHeaderWrapper>
    );
  }

  // 加载完 之后 再加载 此 方法
  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'fund/GetBillGrade',
      payload: formValues,
      callback: response => {
        // let sumMonthInterestAmount = 0, sumProfitValue = 0;
        // for (let i = 0; i < response.list.length; i++) {
        //   sumMonthInterestAmount += parseFloat(response.list[i].monthInterestAmount);
        // }
        response.list.splice(0, 0, {
          billId: '总计',
          monthInterestAmount: 0,
          amountOfMoney: 0,
        });
        const mover = [];
        for (let i = 0; i < document.querySelectorAll('.ant-table-body').length; i++) {
          mover[i] = new Mover(document.querySelectorAll('.ant-table-body')[i]);
        }
      },
    });
  }

  // 改变每页条数和当前页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    if (sorter.field) {
      // 排序参数
      if (sorter.field == 'toStrikePriceRate') {
        formValues.orderItem = 1;
      } else if (sorter.field == 'finalPriceDate') {
        formValues.orderItem = 2;
      } else if (sorter.field == 'discoveryDate') {
        formValues.orderItem = 3;
      } else if (sorter.field == 'billCoupon') {
        formValues.orderItem = 4;
      } else if (sorter.field == 'discountRate') {
        formValues.orderItem = 5;
      } else if (sorter.field == 'amountOfMoney') {
        formValues.orderItem = 6;
      } else {
        formValues.orderItem = 0;
      }
      // formValues.orderItem  = `${sorter.field}`;
      if (sorter.order == 'ascend') {
        formValues.orderType = 1; // 升序
      } else if (sorter.order == 'descend') {
        formValues.orderType = 2; // 降序
      } else {
        formValues.orderType = 0; // 不排序
      }
    } else {
      formValues.orderItem = 0;
      formValues.orderType = 0; // 不排序
    }
    const params = {
      ...formValues,
      ...filters,
    };
    dispatch({
      type: 'fund/GetBillGrade',
      payload: params,
      callback: response => {
        // let sumMonthInterestAmount = 0, sumProfitValue = 0;
        // for (let i = 0; i < response.list.length; i++) {
        //   sumMonthInterestAmount += parseFloat(response.list[i].monthInterestAmount);
        // }
        response.list.splice(0, 0, {
          billId: '总计',
          monthInterestAmount: 0,
          amountOfMoney: 0,
        });
      },
    });
  };

  // 判断 菜单栏 是 缩放显示 还是 全部展示
  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  // 菜单栏- 点击展开显示 事件
  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最大财报日">
              {getFieldDecorator('maxEarningsDate ')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最大财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小财报日">
              {getFieldDecorator('minEarningsDate')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入最小财报日" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小保本幅度">
              {getFieldDecorator('minBreakEvenMargin')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最小权利金">
              {getFieldDecorator('minRoyalty')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="最小收益率">
              {getFieldDecorator('minYieldRate')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  // 菜单栏 默认收缩显示 事件
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.search} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="股票代码">
              {getFieldDecorator('stockId')(
                <Select
                  showSearch
                  style={{ width: '100%' }}
                  placeholder="请输入股票代码"
                  onSearch={this.onSearch.bind(this)}
                  onSelect={this.onSelect.bind(this)}
                >
                  {this.state.suggestions}
                </Select>
              )}
            </FormItem>
          </Col>

          {/*          <Col md={4} sm={20}>
            <FormItem label="来源">
              {getFieldDecorator('billType', {
                initialValue: 0,
              })(
                <Select placeholder="请选择" style={{width: "100%"}}
                        onSelect={this.onSelectType.bind(this)}
                >
                  <Option value={0}>全部</Option>
                  <Option value={1}>RCM</Option>
                  <Option value={2}>Twin Win</Option>
                </Select>
              )}
            </FormItem>
          </Col> */}

          <Col md={4} sm={20}>
            <span className={styles.submitButtons}>
              {/*              <Button type="primary" htmlType="submit" >
                查询
              </Button> */}
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <Button
                style={{ marginLeft: 8 }}
                className={styles.optionsbutton}
                type="primary"
                onClick={() => this.upload(true)}
              >
                瑞银上传
              </Button>
            </span>
          </Col>

          <Col md={4} sm={20}>
            <FormItem label="最小距离执行价">
              {getFieldDecorator('billMinToStrikePriceRate', {
                initialValue: this.state.billMinToStrikePriceRate,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={4} sm={20}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
              <Button style={{ marginLeft: 38 }} type="primary" onClick={this.openBillUpload}>
                上传
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  // 菜单栏-查询按钮 事件
  handleSearch = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      fund: { data },
    } = this.props;
    const { formValues, dataTradeList } = this.state;

    form.validateFields(
      ['maxEarningsDate', 'minEarningsDate', 'minBreakEvenMargin', 'minRoyalty', 'minYieldRate'],
      (err, fieldsValue) => {
        if (err) return;

        const values = {
          ...fieldsValue,
        };
        data.rows = dataTradeList.filter(
          (item, index, arr) => item.stock.indexOf(values.stock.toUpperCase() || '') == 0
        );
        this.setState({
          updateParam: !this.state.updateParam,
        });
      }
    );
  };

  // 菜单栏- 重置按钮 事件
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { formValues } = this.state;
    form.resetFields();
    formValues.stock = '';
    formValues.billType = 0;
    dispatch({
      type: 'fund/GetBillGrade',
      payload: formValues,
      callback: response => {
        this.setState({
          listLoading: false,
        });
        // let sumMonthInterestAmount = 0, sumProfitValue = 0;
        // for (let i = 0; i < response.list.length; i++) {
        //   sumMonthInterestAmount += parseFloat(response.list[i].monthInterestAmount);
        //   // sumProfitValue += parseFloat(response.list[i].profitValue);
        // }
        response.list.splice(0, 0, {
          billId: '总计',
          monthInterestAmount: 0,
          amountOfMoney: 0,
        });
      },
    });
  };

  // 菜单栏- 展开 关闭 事件
  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  upload = () => {
    window.open('/upload/V/DataCenter/RYData.aspx');
  };

  search = e => {
    const { dispatch, form } = this.props;
    const { formValues } = this.state;
    e.preventDefault();

    form.validateFields(['billMinToStrikePriceRate'], (err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      formValues.billMinToStrikePriceRate = values.billMinToStrikePriceRate;

      dispatch({
        type: 'fund/GetBillGrade',
        payload: formValues,
        callback: response => {
          // let sumMonthInterestAmount = 0, sumProfitValue = 0;
          // for (let i = 0; i < response.list.length; i++) {
          //   sumMonthInterestAmount += parseFloat(response.list[i].monthInterestAmount);
          //   // sumProfitValue += parseFloat(response.list[i].profitValue);
          // }
          response.list.splice(0, 0, {
            billId: '总计',
            monthInterestAmount: 0,
            amountOfMoney: 0,
          });
        },
      });
    });
  };

  onSearch(value) {
    /*    const {
              rule: {filterData},
            } = this.props; */
    const { textboxValues, textLoading, suggestions } = this.state;
    this.state.textboxValues.key = value;
    const _this = this;
    // this.state.suggestions=[];
    if (value.length > 0) {
      this.props.dispatch({
        type: 'fund/GetTextBoxList',
        payload: textboxValues,
        callback: () => {
          const suggestionsData = [];
          for (let i = 0; i < _this.props.fund.filterData.list.length; i++) {
            suggestionsData.push(
              <Option key={_this.props.fund.filterData.list[i].address}>
                {_this.props.fund.filterData.list[i].value}
              </Option>
            );
          }
          _this.setState({
            suggestions: suggestionsData,
          });
        },
      });
    }
  }

  onSelect(value) {
    const { dispatch, form } = this.props;
    const { formValues, listLoading } = this.state;

    if (this.state.formValues.stock != undefined) {
      this.setState({
        listLoading: true,
      });
      formValues.stock = value;
      dispatch({
        type: 'fund/GetBillGrade',
        payload: formValues,
        callback: response => {
          this.setState({
            listLoading: false,
          });
          // let sumMonthInterestAmount = 0, sumProfitValue = 0;
          // for (let i = 0; i < response.list.length; i++) {
          //   sumMonthInterestAmount += parseFloat(response.list[i].monthInterestAmount);
          //   // sumProfitValue += parseFloat(response.list[i].profitValue);
          // }
          response.list.splice(0, 0, {
            billId: '总计',
            monthInterestAmount: 0,
            amountOfMoney: 0,
          });
        },
      });
    } else {
      message.warning('股票代码不能为空！');
    }
  }

  onSelectType(value) {
    const { dispatch, form } = this.props;
    const { formValues, listLoading } = this.state;
    console.log(value, 8888);
    if (this.state.formValues.stock != undefined) {
      this.setState({
        listLoading: true,
      });
      formValues.billType = value;
      dispatch({
        type: 'fund/GetBillGrade',
        payload: formValues,
        callback: response => {
          this.setState({
            listLoading: false,
          });
          // let sumMonthInterestAmount = 0, sumProfitValue = 0;
          // for (let i = 0; i < response.list.length; i++) {
          //   sumMonthInterestAmount += parseFloat(response.list[i].monthInterestAmount);
          //   // sumProfitValue += parseFloat(response.list[i].profitValue);
          // }
          response.list.splice(0, 0, {
            billId: '总计',
            monthInterestAmount: 0,
            amountOfMoney: 0,
          });
        },
      });
    } else {
      message.warning('股票代码不能为空！');
    }
  }

  // 平仓modal
  liquidationModalOk() {
    const { pid } = this.state.liquidationRecord;
    this.props.form.validateFields(['liquidationGrade'], (err, values) => {
      if (!err) {
        const { dispatch } = this.props;
        dispatch({
          type: 'fund/BgDeleteBillData',
          payload: {
            id: pid,
            userName: localStorage.getItem('antd-pro-authority').slice(2, -2),
            liquidationRate: values.liquidationGrade,
          },
          callback: res => {
            this.componentDidMount();
          },
        });
      }
    });
  }

  liquidationModalCancel() {
    this.setState({
      liquidationModalVisible: false,
    });
  }

  liquidationCurrentData(record) {
    console.log(record, 'recordfsdsfsf');
    this.setState({
      liquidationRecord: record,
      liquidationModalVisible: true,
    });
  }
}

export default MGHGBill;
